const express=require('express');
const r=express.Router();
const pool=require('../util/pool.js');
const check=require('../util/selfFun.js');

// http://127.0.0.1:8080/v1/orDetails/upload
r.post('/upload',(req,res,next)=>{
    let obj=req.body;
    let isnull=check.isNull(obj);
    console.log('isnull: ', isnull);
    if(isnull!=='no'){
        res.send(isnull);
        return;
    }
    pool.query('insert into xz_order_detail set ?',[obj],(err,results)=>{
        if(err){
            next(err);
            return;
        }
        console.log(results);
        if(results.affectedRows===0){
        res.send({code:400,msg:'上传失败！'});
            return;
    }
    res.send({code:200,msg:'上传成功！'});
    });
    // res.send({code:200,msg:'上传成功！'});
});


r.put('/update',(req,res,next)=>{
    let obj=req.body;
    let isnull=check.isNull(obj);
    if(isnull!=='no'){
        res.send(isnull);
        return;
    }
    pool.query('update xz_order_detail set ?',[obj],(err,results)=>{
        if(err){
            next(err);
            return;
        }
        if(results.changedRows===0){
            res.send({code:400,msg:'修改失败！'});
            return;
        }
        res.send({code:200,msg:'修改成功！'})
    });
    // res.send({code:200,msg:'修改成功！'});
});

// http://127.0.0.1:8080/v1/orDetails/delete 2002
r.delete('/delete:did',(req,res,next)=>{
    let did=req.params.did;
    pool.query('delete from xz_order_detail where did=?',[did],(err,results)=>{
        if(err){
            next(err);
            return;
        }
        if(results.affectedRows===0){
            res.send({code:400,msg:'删除失败！'});
            return;
        }
        res.send({code:200,msg:'删除成功！'});
    });
    // res.send({code:200,msg:'删除成功！'});
});

// http://127.0.0.1:8080/v1/orDetails/list?pages=1&num=1
r.get('/list',(req,res,next)=>{
    let pages=parseInt(req.query.page);
    let num=parseInt(req.query.num);
    console.log(pages);
    if(!num){
        num=5;
    }
    if(!pages){
        pages=0;
    }
    pages=(pages-1)*num;
    pool.query('select * from xz_order_detail limit ?,?',[pages,num],(err,results)=>{
        if(err){
            next(err);
            return;
        }
        console.log('results: ', results);
        if(results){
        res.send({code:200,msg:'查询成功！'});
        return;
    }else{
        res.send({code:400,msg:'查询失败！'});
    }
    
    });
    // res.send({code:200,msg:'查询成功！'});
});
//获取所有订单信息
r.get('/list2',(req,res,next)=>{
    pool.query('select * from xz_order_detail ',(err,results)=>{
        if(err){
            next(err);
            return;
        }
        // console.log('results: ', results);//Object
        if(results){
        // res.send({code:200,msg:'查询成功！'});
        res.send(results);
        return;
    }else{
        res.send({code:400,msg:'查询失败！'});
    }
    
    });
    // res.send({code:200,msg:'查询成功！'});
});
module.exports=r;